﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MealCardManagement.Client
{
    public partial class UserList : UserControl
    {
        private User[] AllUsers;

        public UserList()
        {
            InitializeComponent();
        }

        private void UserList_Load(object sender, EventArgs e)
        {
            listViewUser.Columns[0].Width = 40;
            listViewUser.Columns[1].Width = listViewUser.Width - 40 - 4;
        }

        public void SetUsers(IEnumerable<User> users)
        {
            this.AllUsers = users.ToArray();
            RefreshList(AllUsers);
        }

        private void RefreshList(IEnumerable<User> users)
        {
            listViewUser.Items.Clear();
            foreach (var user in users)
            {
                var item = new ListViewItem(user.Id.ToString());
                item.SubItems.Add(user.Name);
                listViewUser.Items.Add(item);
            }
        }

        private void listViewUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectId = SelectedUserId;
            btnDelete.Enabled = selectId != null;
            SelectUser?.Invoke(this, selectId);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            using (var nameInput = new NameInputForm())
            {
                if (nameInput.ShowDialog() != DialogResult.OK)
                    return;
                var name = nameInput.InputName;
                NewUser?.Invoke(this, name);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            var id = SelectedUserId.Value;
            DeleteUser?.Invoke(this, id);
        }

        private void textBoxFilter_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBoxFilter.Text))
                RefreshList(AllUsers);
            else
                RefreshList(AllUsers.Where(x => x.Name.Contains(textBoxFilter.Text) || x.Id.ToString().Contains(textBoxFilter.Text)));
        }

        public int? SelectedUserId
        {
            get
            {
                if (listViewUser.SelectedItems.Count == 0)
                    return null;
                else
                    return int.Parse(listViewUser.SelectedItems[0].Text);
            }
        }
            

        public event Action<UserList,string> NewUser;
        public event Action<UserList, int> DeleteUser;
        public event Action<UserList, int?> SelectUser;


    }
}
